package com.webdrider.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Sorter {
	
	public static <K, V extends Comparable<? super V>> List<K> sortKeysByValue(Map<K, V> map) {
		List<Map.Entry<K, V>> sortList = new ArrayList<Map.Entry<K,V>>();
		List<K> result = new ArrayList<K>();
		MapComparator<V> comparator = new MapComparator<V>();
		
		sortList.addAll(map.entrySet());
		Collections.sort(sortList, comparator);
		
		for (int i = 0; i < sortList.size(); i++) {
			result.add(sortList.get(i).getKey());
		}
		
		return result;
	}
	
	private static class MapComparator<V extends Comparable<? super V>> implements Comparator<Map.Entry<?, V>> {

		@Override
		public int compare(Entry<?, V> value1, Entry<?, V> value2) {
			return value1.getValue().compareTo(value2.getValue());
		}

	}
}
